<template>
    <div class="login">
      <div class="login-form">
        <h1>登录账户</h1>
        <div class="form-contolr"><Input v-model="formItem.user" size="large" placeholder="请输入用户名" /></div>
        <div class="form-contolr"><Input v-model="formItem.password" type="password" size="large" placeholder="请输入密码" /></div>
        <div class="form-contolr">
          <RadioGroup v-model="role">
            <Radio label="teacher"><span>老师</span></Radio>
            <Radio label="student"><span>学生</span></Radio>
            <Radio label="root"><span>教务</span></Radio>
          </RadioGroup>
        </div>
        <div class="form-contolr form-contolr-btn"><Button :loading="loading" @click="login()" shape="circle" size="large" type="primary" long>登录</Button></div>
        <p class="errmsg">{{errmsg}}</p>
        <p class="forget"><router-link to="/">忘记密码？</router-link></p>
      </div>
    </div>
</template>
<script>
export default{
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (window.localStorage.user) {
        vm.$router.push('/')
      }
    })
  },
  data() {
    return {
      errmsg: '',
      loading: false,
      role: 'teacher',
      formItem: {
        user: '',
        password: ''
      },
    }
  },
  methods: {
    login() {
      let { user, password } = this.formItem
      this.errmsg = ''
      if (user.trim() === '' || user.length < 6) {
        this.errmsg = '用户名格式错误'
        return
      }
      if (password.trim() === '' || password.length < 6 || password.length > 16) {
        this.errmsg = '密码格式错误'
        return
      }

      this.loading = true
      let userInfo = {
        username: '陈xx',
        uid: 20,
        role: this.role
      }
      this.$store.commit('setUser', userInfo)

      //将登录数据保存在session中
      window.localStorage.user = JSON.stringify(userInfo)

      // 跳转到登录前的页面
      let redirect = decodeURIComponent(this.$route.query.redirect || '/')
      this.$router.push({
        path: redirect
      })
    }
  }
}
</script>
<style scoped>
  .login{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    min-width: 1200px;
    min-height: 500px;
    background: #eeeeee url("../../static/img/login-register.jpg") center no-repeat;
    background-size: cover;
  }
  .login-form{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -200px;
    margin-top: -190px;
    width: 400px;
    background: #fff;
    padding: 20px;
    text-align: left;
    height: 380px;
    box-shadow: 0 0 30px rgba(0,0,0,0.1);

    text-align: center;
  }
  .login-form h1{
    font-size: 20px;
    font-weight: inherit;
    margin-bottom: 40px;
    display: block;

    text-align: left;
  }
  .form-contolr{
    margin-top: 20px;
  }
  .form-contolr-btn {
    margin-top: 35px;
  }
  .errmsg{
    line-height: 40px;
    height: 40px;
    color: #ed3f14;
  }
  .forget{
    line-height: 50px;
  }
</style>
